package config;

import java.util.Date;
import java.util.Properties;
import java.io.*;

import error.*;

public class Config {
	private static String identifier = "earlyBird.config.Config";
	
	private static String configFile = "earlybird.conf";
	private static Properties prop = new Properties();
	
	static {
		try {
			loadFile();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	}
	
	public static void loadFile() throws Exception{
		try {
			prop.load(new FileInputStream(configFile));
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace(System.err);
			createFile();
			loadFile();
		} catch (IOException ioe) {
			ioe.printStackTrace(System.err);
			// TODO: error and quit?
		}
	}
	
	public static void createFile() throws Exception {
		// TODO: add key-value pairs
		prop = new Properties();
		prop.put("bufferManager", "LRUBufferManager");
		prop.put("fileManager", "FileManager");
		prop.put("heapfile", "earlyBird.hf");
		prop.put("blockSize", "4096");
		prop.put("BTreePointerCount", "4");
		//---------------------------Shadow
		
		
		prop.store(new FileOutputStream(configFile), new Date().toString());
	}
	
	public static int getInteger(String key) throws EBConfigException {
		if (prop.containsKey(key)) {
			String str = prop.getProperty(key);
			int value;
			try {
				value = Integer.parseInt(str);
			} catch (NumberFormatException nfe) {
				nfe.printStackTrace(System.err);
				throw new EBConfigException(identifier + ": getInteger (type mismatch)");
			}
			return value;
		} else
			throw new EBConfigException(identifier + ": getInteger (no such key)");
	}
	
	public static int getInteger(String key, int defVaule) {
		try {
			return getInteger(key);
		} catch (EBConfigException e) {
			return defVaule;
		}
	}
	
	public static String getString(String key) throws EBConfigException {
		if (prop.containsKey(key))
			return prop.getProperty(key);
		else
			throw new EBConfigException(identifier + ": getString (no such key)");
	}
	
	public static String getString(String key, String defValue) {
		try {
			return getString(key);
		} catch (EBConfigException e) {
			return defValue;
		}
	}
}
